<template>
    <!-- 导航 -->
    <el-breadcrumb class="navigation" separator="/">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>排班管理</el-breadcrumb-item>
        <el-breadcrumb-item>班组设置</el-breadcrumb-item>
    </el-breadcrumb>
    <div class="headDivider"></div>
    <div class="flex">
        <!--  搜索栏 -->
        <div>
            <el-form style="margin-top: 15px;" :inline="true" :model="queryTeam" class="demo-form-inline">
                <el-form-item label="班组类型">
                    <el-select v-model="queryTeam.teamTypeId" placeholder="班组类型">
                        <el-option v-for="item in types" :key="item.teamTypeId" :label="item.teamTypeName"
                            :value="item.teamTypeId"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="班组编号">
                    <el-input v-model="queryTeam.teamCode" placeholder="班组编号" clearable />
                </el-form-item>
                <el-form-item label="班组名称">
                    <el-input v-model="queryTeam.teamName" placeholder="班组名称" clearable />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="loadTeams">搜索</el-button>
                    <el-button @click="resetTing">重置</el-button>
                </el-form-item>
            </el-form>
        </div>
        <!-- 工具栏 -->
        <div>
            <el-button title="新增班组" @click="this.addTeamDialogVisible = true" type="primary"><el-icon>
                    <Plus />
                </el-icon></el-button>
            <el-button title="编辑选中班组" @click="handlerTeamEdits" type="primary"><el-icon>
                    <EditPen />
                </el-icon></el-button>
            <el-button @click="deleteTeamEdits" title="删除选中班组" type="danger"><el-icon>
                    <Delete />
                </el-icon></el-button>
        </div>
    </div>

    <!-- 数据表格 -->
    <el-table ref="teamTable" :row-key="(row) => row.teamId" :data="teams" style="width: 100%">
        <el-table-column :reserve-selection="true" type="selection" width="55" />
        <el-table-column label="班组编码" property="teamCode" />
        <el-table-column label="班组名称" property="teamName" />
        <el-table-column label="班组类型" property="teamTypeId">
            <template #default="scope">
                <span v-if="scope.row.teamTypeId == 1">搬砖</span>
                <span v-else-if="scope.row.teamTypeId == 2">拿瓦</span>
                <span v-else-if="scope.row.teamTypeId == 3">和泥</span>
                <span v-else-if="scope.row.teamTypeId == 4">炒菜</span>
                <span v-else type="success">刷碗</span>
            </template>
        </el-table-column>
        <el-table-column label="备注" property="remark" />

        <el-table-column width="330" align="center" label="操作">
            <template #default="scope">
                <el-button size="small" @click="handleTeamEdit(scope.row)">编辑</el-button>
                <el-button size="small" type="danger" @click="deleteTeamEdits(scope.row)">删除</el-button>
            </template>
        </el-table-column>
    </el-table>
    <!-- 分页栏 -->
    <el-pagination class="page" :page-size="limit" @current-change="changePage" background layout="prev, pager, next"
        :total="total" />

    <!-- 删除确认框 -->
    <!-- <el-dialog v-model="deleteTeamDialogVisible" title="确认" width="30%">
        <span>确认删除选中权限及其子权限</span>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="canceDeletelEdit">取消</el-button>
                <el-button type="primary" @click="deleteTeamEdit">确认</el-button>
            </span>
        </template>
    </el-dialog> -->

    <!-- 添加班组的弹窗-->
    <el-dialog v-model="addTeamDialogVisible" title="添加用户" :destroy-on-close=true width="900" align-center
        @close="cancelAddTeam">
        <el-form label-width="100px" :model="newTeam" style="max-width: 850px">
            <div class="addTeam">
                <span>*</span>
                <el-form-item label="班组编号" style="width: 300px;">
                    <el-input v-model="newTeam.teamCode" />
                </el-form-item>
                <span>*</span>
                <el-form-item label="班组名称" style="width: 300px;">
                    <el-input v-model="newTeam.teamName" />
                </el-form-item>
                <span>*</span>
                <el-form-item label="班组类型" style="width: 210px;">
                    <el-select v-model="newTeam.teamTypeId" placeholder="班组类型">
                        <el-option v-for="item in types" :key="item.teamTypeId" :label="item.teamTypeName"
                            :value="item.teamTypeId"></el-option>
                    </el-select>
                </el-form-item>
            </div>
            <el-form-item label="备注">
                <el-input type="textarea" v-model="newTeam.remark" />
            </el-form-item>
        </el-form>
        <div class="divider">
            <div class="divider-text">项目组成员</div>
        </div>
        <!-- 项目成员工具栏 -->
        <div>
            <el-button title="新增用户" @click="addUserEdits" type="primary"><el-icon>
                    <Plus />
                </el-icon></el-button>
            <el-button @click="deleteUserEdits" title="删除选中用户" type="danger"><el-icon>
                    <Delete />
                </el-icon></el-button>
        </div>

        <!-- 用户表格 -->
        <el-table ref="teamUserTable" :data="teamUser" style="width: 100%">
            <el-table-column type="selection" width="55" />
            <el-table-column label="用户编号" property="userId" />
            <el-table-column label="用户名称" property="userName" />
            <el-table-column label="用户昵称" property="userNickName" />
            <el-table-column label="手机号码" property="tel" />
            <el-table-column label="操作">
                <template #default="scope">
                    <el-button size="small" type="danger" @click="deleteTeamUser(scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <template #footer>
            <span class="dialog-footer">
                <el-button @click="cancelAddTeam">取消</el-button>
                <el-button type="primary" @click="doAddTeam">提交</el-button>
            </span>
        </template>
    </el-dialog>

    <!-- 用户数据 -->
    <el-dialog v-model="addUserDialogVisible" title="人员选择" width="70%" align-center @close="cancelAddUser">
        <div class="data">
            <!-- 部门树状图 -->
            <div class="tree">
                <el-tree :expand-on-click-node="false" ref="departmentTree" :data="departments" node-key="departmentId"
                    :props="defaultProps" :default-expand-all="true" style="margin-top: 15px;"
                    @node-click="selectUserBydepartmentId" />
            </div>
            <div class="user">
                <!-- 人员信息 -->
                <el-table ref="userTable" :data="users" style="width: 100%" #default="scope">
                    <el-table-column type="selection" width="55" />
                    <el-table-column label="用户编号" property="userId" />
                    <el-table-column label="用户名称" property="userName" />
                    <el-table-column label="用户昵称" property="userNickName" />
                    <el-table-column label="部门" property="" />
                    <el-table-column label="手机号码" property="tel" />
                    <el-table-column label="状态" property="userStatus" />
                    <!-- <el-table-column label="创建时间" property="createTime" /> -->
                </el-table>
            </div>
        </div>
        <!-- 分页栏 -->
        <el-pagination class="page" :page-size="limit" @current-change="changeUserPage" background
            layout="prev, pager, next" :total="userTotal" />

        <template #footer>
            <span class="dialog-footer">
                <el-button @click="cancelAddUser">取消</el-button>
                <el-button type="primary" @click="doAddUser">提交</el-button>
            </span>
        </template>
    </el-dialog>

    <!-- 编辑班组的弹窗 -->
    <el-dialog v-model="updateTeamDialogVisible" title="编辑班组" :destroy-on-close=true width="900" align-center
        @close="cancelAddTeam">
        <el-form label-width="100px" :model="updateTeam" style="max-width: 850px">
            <div class="addTeam">
                <span>*</span>
                <el-form-item label="班组编号" style="width: 300px;">
                    <el-input v-model="updateTeam.teamCode" />
                </el-form-item>
                <span>*</span>
                <el-form-item label="班组名称" style="width: 300px;">
                    <el-input v-model="updateTeam.teamName" />
                </el-form-item>
                <span>*</span>
                <el-form-item label="班组类型" style="width: 210px;">
                    <el-select v-model="updateTeam.teamTypeId" placeholder="班组类型">
                        <el-option v-for="item in types" :key="item.teamTypeId" :label="item.teamTypeName"
                            :value="item.teamTypeId"></el-option>
                    </el-select>
                </el-form-item>
            </div>
            <el-form-item label="备注">
                <el-input type="textarea" v-model="updateTeam.remark" />
            </el-form-item>
        </el-form>
        <div class="divider">
            <div class="divider-text">项目组成员</div>
        </div>
        <!-- 项目成员工具栏 -->
        <div>
            <el-button title="新增用户" @click="addUserEdits" type="primary"><el-icon>
                    <Plus />
                </el-icon></el-button>
            <el-button @click="deleteUserEdits" title="删除选中用户" type="danger"><el-icon>
                    <Delete />
                </el-icon></el-button>
        </div>
        <!-- 用户表格 -->
        <el-table ref="TeamUserTable" :data="teamUser" style="width: 100%">
            <el-table-column type="selection" width="55" />
            <el-table-column label="用户编号" property="userId" />
            <el-table-column label="用户名称" property="userName" />
            <el-table-column label="用户昵称" property="userNickName" />
            <el-table-column label="手机号码" property="tel" />
            <el-table-column label="操作">
                <template #default="scope">
                    <el-button size="small" type="danger" @click="deleteTeamUser(scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <template #footer>
            <span class="dialog-footer">
                <el-button @click="cancelUpdateTeam">取消</el-button>
                <el-button type="primary" @click="doUpdateTeam">提交</el-button>
            </span>
        </template>
    </el-dialog>
</template>

<script>
import teamRequest from '../../../api/cal-team.js';
import teamTypeRequest from '../../../api/cal-teamType.js';
import departmentRequest from '../../../api/cal-department.js';
import userRequest from '../../../api/cal-user.js';
import teamMemberRequest from '../../../api/cal-teamMember.js';
export default {
    data() {
        return {
            //加载数据
            teams: [],//班组数据列表
            queryTeam: {},//多条件查询的数据列表
            types: [],//班组类型列表
            page: 1,// 分页的当前页码
            limit: 10,// 分页的每页大小
            total: 0,// 列表的总条数
            maxPageNum: 1,// 列表的最大页码

            //添加班组
            addTeamDialogVisible: false,
            newTeam: {},
            addUserDialogVisible: false,//人员选择弹窗
            teamUser: [],//班组成员
            //部门数据
            departments: [],
            defaultProps: {
                children: 'children',// 孩子节点集合的属性名
                label: 'departmentName',// 对应的文本的属性名
            },
            //用户数据
            users: [],
            queryUser: {},
            userPage: 1,//当前页数
            userTotal: 0,// 列表的总条数
            userMaxPageNum: 1,// 列表的最大页码

            //编辑班组
            updateTeam: [],
            updateTeamDialogVisible: false,
        }
    }, methods: {
        /**
         * 删除班组
         */
        deleteTeamEdits(row) {
            let teamCodes = [];
            let table = this.$refs.teamTable.getSelectionRows();
            //批量删除
            if (row.teamCode == undefined || row.teamCode == "") {
                if (table == undefined || table.length == 0) {
                    this.$message({
                        type: "info",
                        message: "请选择至少一行"
                    });
                }
                table.forEach(table => {
                    teamCodes.push(table.teamCode)
                });
                teamRequest.deleteById(teamCodes, res => {
                    if (res.code != 0) {
                        this.$message({
                            type: "success",
                            message: "删除成功"
                        });
                    }
                    this.loadTeams();//班组数据
                });
            }

            //单行删除
            teamCodes.push(row.teamCode);
            teamRequest.deleteById(teamCodes, res => {
                if (res.code != 0) {
                    this.$message({
                        type: "success",
                        message: "删除成功"
                    });
                }
                this.loadTeams();//班组数据
            })


        },
        //批量编辑,只编辑选中的第一个用户
        handlerTeamEdits() {
            let one = this.$refs.teamTable.getSelectionRows();
            if (one.length != 0) {
                let row = one[0];
                this.handleTeamEdit(row);
            }
        },
        /**
         * 提交编辑班组信息
         */
        doUpdateTeam() {
            if (this.updateTeam.teamCode == null || this.updateTeam.teamName == null || this.updateTeam.teamTypeId == null) {
                this.$message({
                    message: '请输入必填项',
                    type: 'warning',
                });
                return;
            }
            //如果用户数据被删除,则提交的时候,将数据表和最新的用户数据不一致的数据删除
            let allTeamUser = [];
            let memberIds = [];
            teamMemberRequest.list(this.updateTeam.teamCode, res => {
                allTeamUser = res.data;
                allTeamUser.forEach(teamUser => {
                    memberIds.push(teamUser.memberId);
                });
                for (let index = 0; index < memberIds.length; index++) {
                    for (let j = 0; j < this.teamUser.length; j++) {
                        if (memberIds[index] == undefined || memberIds[index] == null) {
                            break;
                        }
                        if (memberIds[index] == this.teamUser[j].memberId) {
                            memberIds.splice(index, 1);
                            index--;
                        }
                    }
                }

                // 提交最新的用户数据
                if (memberIds.length != 0) {
                    teamMemberRequest.deleteByIds(memberIds, res => { });
                }

                if (!this.teamUser.length == 0 || this.teamUser == undefined) {
                    teamMemberRequest.save(this.updateTeam.teamCode, this.teamUser, res => {
                        if (res.code == 200) {
                            this.teamUser = [];
                        }
                    });
                }
            });

            teamRequest.update(this.updateTeam, res => {
                if (res.code == '1') {
                    this.$message({
                        message: '修改成功',
                        type: 'success'
                    });
                    //关闭窗体
                    this.updateTeamDialogVisible = false;
                    // 重新加载数据
                    this.loadTeams();
                    // 将newUser制空
                    this.newTeam = {};
                } else if (res.code == '300') {
                    this.$message({
                        message: '班组名称重复',
                        type: 'warning',
                    });
                } else {
                    this.$message({
                        message: '修改失败',
                        type: 'error',
                    });
                }
            });
        },
        /**
        * 取消提交编辑班组信息
        */
        cancelUpdateTeam() {
            this.updateTeamDialogVisible = false;
            this.newTeam = {};
            //取消所有选中行
            this.loadUser();
        },
        /**
         * 编辑班组
         */
        handleTeamEdit(row) {
            teamRequest.selectByTeamId(row.teamId, res => {
                this.updateTeam = res.data;
            });
            teamMemberRequest.list(row.teamCode, res => {
                this.teamUser = res.data;
                this.updateTeamDialogVisible = true;
            })
        },

        /**
         * 添加班组
         */
        doAddTeam() {
            if (this.newTeam.teamCode == null || this.newTeam.teamName == null || this.newTeam.teamTypeId == null) {
                this.$message({
                    message: '请输入必填项',
                    type: 'warning',
                });
                return;
            }
            if (!this.teamUser.length == 0 || this.teamUser == undefined) {
                teamMemberRequest.save(this.newTeam.teamCode, this.teamUser, res => {
                    if (res.code == 200) {
                        this.teamUser = [];
                    }
                });
            }
            teamRequest.save(this.newTeam, res => {
                if (res.code == '1') {
                    this.$message({
                        message: '添加班组成功',
                        type: 'success'
                    });
                    //关闭窗体
                    this.addTeamDialogVisible = false;
                    // 重新加载数据
                    this.loadTeams();
                    // 将newUser制空
                    this.newTeam = {};
                } else if (res.code == '300') {
                    this.$message({
                        message: '班组名称重复',
                        type: 'warning',
                    });
                } else {
                    this.$message({
                        message: '添加失败',
                        type: 'error',
                    });
                }
            });

        },
        /**
         * 取消添加
         */
        cancelAddTeam() {
            this.addTeamDialogVisible = false;
            // 将newUser制空
            this.newTeam = {};
            //取消所有选中行
            this.loadUser();
        },
        /**
         * 批量删除添加班组中的用户
         */
        deleteUserEdits() {
            // 通过API获取被选中的数据 
            let table = this.$refs.teamUserTable.getSelectionRows();
            let deleteUserId = [];
            table.forEach(user => {
                deleteUserId.push(user.userId)
            });
            for (let i = 0; i < this.teamUser.length; i++) {
                for (let j = 0; j < deleteUserId.length; j++) {
                    if (deleteUserId[j] == this.teamUser[i].userId) {
                        this.teamUser.splice(i, 1);
                    }
                }
            }
        },
        /**
         * 添加班组中的删除用户
         */
        deleteTeamUser(row) {
            for (let index = 0; index < this.teamUser.length; index++) {
                if (row.userId == this.teamUser[index].userId) {
                    this.teamUser.splice(index, 1);
                    index--;
                }
            }
        },
        /**
         *添加用户进班组 
         */
        doAddUser() {
            //判断用户是否已经存在
            let table = this.$refs.userTable.getSelectionRows();
            let allTeamUser = [];
            teamMemberRequest.getAll(res => {
                let userName = "";
                allTeamUser = res.data;
                //选中的用户跟班组用户表中全部的树据进行比较
                for (let index = 0; index < table.length; index++) {
                    for (let j = 0; j < allTeamUser.length; j++) {
                        if (table[index] == undefined || table[index] == null) {
                            break;
                        }
                        if (table[index].userId == allTeamUser[j].userId) {
                            userName += table[index].userName + " ";
                            table.splice(index, 1);
                            index--;
                        }
                    }
                }
                //选中的用户跟此班组已经存在用户树据进行比较
                for (let index = 0; index < table.length; index++) {
                    for (let j = 0; j < this.teamUser.length; j++) {
                        if (table[index] == undefined || table[index] == null) {
                            break;
                        }
                        if (table[index].userId == this.teamUser[j].userId) {
                            userName += table[index].userName + " ";
                            table.splice(index, 1);
                            index--;
                        }
                    }
                }
                if (table.length != 0 || table != undefined) {
                    table.forEach(table => {
                        this.teamUser.push(table);
                    });
                }
                if (userName != "") {
                    this.$message({
                        message: userName + '已存在',
                        type: 'warning',
                    });
                }
                this.addUserDialogVisible = false;
            });
        },
        /**
        *取消用户进班组 
        */
        cancelAddUser() {
            this.addUserDialogVisible = false;
        },
        /**
         * 按照部门id查询用户
         */
        selectUserBydepartmentId(data) {
            userRequest.selectByDepartmentId(data.departmentId, data => {
                this.users = data.data;
            })
        },
        /**
         * 获取用户数据
         */
        loadUser() {
            userRequest.list(this.userPage, this.limit, this.queryUser, data => {
                this.users = data.data.list;
                this.userTotal = data.data.total;
                this.userMaxPageNum = data.data.pages;
            })

        },
        changeUserPage(currPage) {//更新用户分页
            this.userPage = currPage;
            this.loadUser();
        },
        /**
         * 获取部门数据
         */
        loadDepartment() {
            departmentRequest.list(this.page, this.limit, res => {
                this.departments = res.data;
            })

        },
        /**
         * 打开用户数据界面
         */
        addUserEdits() {
            this.loadUser();
            this.addUserDialogVisible = true;
        },
        /**
         * 获取班组类型
         */
        loadTeamTypes() {
            teamTypeRequest.list(data => {
                this.types = data.data.data;
            });
        },
        /**
         * 重置按钮
         */
        resetTing() {
            this.queryTeam = {};
            this.loadTeams();
        },
        /**
         *获取列表数据
         */
        loadTeams() {
            teamRequest.list(this.page, this.limit, this.queryTeam, data => {
                this.teams = data.data.list;
                this.total = data.data.total;
                this.maxPageNum = data.data.pages;
            });
        }, 
        /**
         *更新分页
         */
        changePage(currPage) {//更新分页
            this.page = currPage;
            this.loadTeams();
        }
    }, mounted() {
        this.loadTeams();//班组数据
        this.loadTeamTypes();//班组类型
        this.loadDepartment();//部门数据
        this.loadUser();//用户数据
    }
}
</script>

<style scoped>
.page {
    margin-top: 10px;
    justify-content: center;
}

.addTeam {
    display: flex;
    justify-content: flex-start;
}

.addTeam span {
    color: #ff4949;
    line-height: 35px;
    position: relative;
    right: -25px;
}

.divider {
    display: block;
    height: 1px;
    width: 100%;
    margin: 24px 0;
    background-color: #dcdfe6;
    position: relative;
}

.headDivider {
    display: block;
    height: 1px;
    width: 100%;
    margin: 24px 0;
    background-color: #dcdfe6;
    position: relative;
}

.divider-text {
    position: absolute;
    background-color: #fff;
    padding: 0 20px;
    font-weight: 500;
    color: #303133;
    font-size: 14px;
    bottom: -8px;
    left: 370px;
}

.data {
    margin-top: -30px;
    width: 100%;
    display: flex;
    justify-content: flex-start;
}

.user {
    width: 800px;
}

.tree {
    margin-top: 1px;
    height: 520px;
    width: 200px;
}
</style>